/*
 * Copyright 2007-2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 * 
 * Project: gtinyurl
 */
package org.gnut.tinyurl.portlet.tag;

import javax.portlet.PortletURL;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.gnut.tinyurl.portlet.TinyPortlet;

/**
 * 
 * @author tungt
 * 
 */
public class PortletTagSupport implements UrlTagSupport {
	public static final String PORTLET_REQUEST_ATTRIBUTE = "javax.portlet.request";
	public static final String PORTLET_RESPONSE_ATTRIBUTE = "javax.portlet.response";
	public static final String __tiny_uri__ = "__tiny_uri__";

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.gnut.tinyurl.portlet.tag.UrlTagSupport#createUrl(javax.servlet.http
	 * .HttpServletRequest, javax.servlet.http.HttpServletResponse, boolean,
	 * java.lang.String)
	 */
	public String createUrl(HttpServletRequest request,
			HttpServletResponse response, boolean isResource, String uri)
			throws Exception {
		RenderRequest renderRequest = (RenderRequest) request
				.getAttribute(PORTLET_REQUEST_ATTRIBUTE);
		RenderResponse renderResponse = (RenderResponse) request
				.getAttribute(PORTLET_RESPONSE_ATTRIBUTE);

		if (renderRequest == null || renderResponse == null) {
			throw new Exception("Can't find Portlet attribute in Request !!!");
		}
		String prefix = (request.isSecure() ? "https://" : "http://")
				+ request.getServerName() + ":" + request.getServerPort();

		if (isResource) {
			return prefix
					+ renderResponse.encodeURL(renderRequest.getContextPath()
							+ ((uri != null && uri.startsWith("/")) ? uri : "/"
									+ uri));
		} else {
			PortletURL portletURL = renderResponse.createRenderURL();
			portletURL.setParameter(__tiny_uri__,
					((uri != null && uri.startsWith("/")) ? uri : "/" + uri));
			portletURL.setParameter(TinyPortlet.portlet_mode, renderRequest
					.getPortletMode().toString());
			return prefix + portletURL.toString();
		}
	}

}
